/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Mobilottery.Utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 *
 * @author WindowsVista
 */
public class UtilsConnection
{

    public static String GetData(String p_url)
    {
        HttpConnection connection = null;
        InputStream inputstream = null;
        try
        {
            connection = (HttpConnection) Connector.open(p_url, Connector.READ, true);
            //HTTP Request
            connection.setRequestMethod(HttpConnection.GET);
            connection.setRequestProperty("Content-Type", "//text plain");
            connection.setRequestProperty("Connection", "close");
            // HTTP Response
            //System.out.println("Status Line Code: " + connection.getResponseCode());
            //System.out.println("Status Line Message: " + connection.getResponseMessage());
            if (connection.getResponseCode() == HttpConnection.HTTP_OK)
            {
                //System.out.println(connection.getHeaderField(0) + " " + connection.getHeaderFieldKey(0));
                //System.out.println("Header Field Date: " + connection.getHeaderField("date"));
                String str;
                inputstream = connection.openInputStream();
                int length = (int) connection.getLength();
                if (length != -1)
                {
                    byte incomingData[] = new byte[length];
                    inputstream.read(incomingData);
                    str = new String(incomingData);
                }
                else
                {
                    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                    int ch;
                    while ((ch = inputstream.read()) != -1)
                    {
                        bytestream.write(ch);
                    }
                    str = new String(bytestream.toByteArray());
                    bytestream.close();
                }
                //System.out.println(str);
                return str;
            }
        }
        catch (Exception error)
        {
            // System.out.println("Caught IOException: " + error.toString());
        }
        finally
        {
            if (inputstream != null)
            {
                try
                {
                    inputstream.close();
                }
                catch (Exception error)
                {
                    /*log error*/
                }
            }
            if (connection != null)
            {
                try
                {
                    connection.close();
                }
                catch (Exception error)
                {
                    /*log error*/
                }
            }
        }
        return null;
    }
}
